package cn.regexp.resolver;

import cn.regexp.annotation.UserParam;
import cn.regexp.domain.ShopUser;
import cn.regexp.redis.service.IShopUserRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;


/**
 * 自定义用户对象参数解析器
 */
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver {
    @Autowired
    private IShopUserRedisService userRedisService;
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        /**
         * 判断参数的类型是否为 UserInfo
         *    && 判断参数是否贴了指定注解（目的是为了区分使用默认参数解析器或自定义参数解析器）
         */
        return parameter.getParameterType() == ShopUser.class
                && parameter.hasParameterAnnotation(UserParam.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter,
                                  ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest,
                                  WebDataBinderFactory binderFactory) throws Exception {
        /**
         * 通过 webRequest 对象获取 token
         * webRequest -->
         * HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
         */
        String token = webRequest.getHeader("token");
        if (token != null) {
            // 通过 token 获取用户对象并返回
            return userRedisService.getUserByToken(token);
        }
        return null;
    }
}
